"""
@File    :   app.py
@Time    :   2024/01/07 20:00:35
@Author  :   Qrj
@Email   :   923207736@qq.com
@description   :   应用及其注册文件
"""

from fastapi import FastAPI


def create_app() -> FastAPI:
    """创建Fastapi实例

    Returns:
        FastAPI: Fastapi实例
    """
    from src.app.path import mount_static_and_upload_path
    from src.app.router import register_routers
    from src.app.swagger import static_app_api_docs
    from src.config import get_app_settings
    from src.exceptions.register import register_global_exceptions_handler
    from src.lifespan.register import register_lifespan
    from src.middlewares.register import register_middleware

    # 获取应用配置
    settings = get_app_settings()
    # 根据配置设置swagger是否使用在线的css、js等资源
    if settings.api_openapi_static_enable:
        docs_url, redoc_url = None, None
    else:
        docs_url, redoc_url = settings.api_docs_url, settings.api_redoc_url
    # 创建App
    app = FastAPI(
        title=settings.api_doc_title,
        description=settings.api_doc_description,
        version=settings.api_version,
        debug=settings.debug,
        openapi_prefix="",
        openapi_url=settings.api_openapi_url,
        docs_url=docs_url,
        redoc_url=redoc_url,
        terms_of_service=settings.api_terms_of_service,
        contact=settings.api_contact,
        license_info=settings.api_license_info,
        servers=settings.api_server,
        lifespan=register_lifespan,  # 注册app的启动与关闭事件
    )
    # 注册app的全局异常处理
    register_global_exceptions_handler(app)
    # 注册中间件
    register_middleware(app)
    # 为app配置静态资源与上传文件资源
    mount_static_and_upload_path(app)
    # 让swagger的css与js文件从本地加载
    static_app_api_docs(app)
    # 注册路由
    register_routers(app)
    return app


# 创建APP实例, 用于给uvicorn调用
app = create_app()
